import uuid
from flaskapp.model.db import db, Dictionary
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime
import logging

# Setup logging
logger = logging.getLogger(__name__)


def insert(category: str, key: str, value: str) -> bool:
    try:
        current_datetime = datetime.now()
        info = Dictionary(id=str(uuid.uuid4()),pid=None, category=category,
                          key=key, value=value, timestamp=current_datetime)
        db.session.add(info)
        db.session.commit()
        logger.info(f"Inserted dict with id: {info.id}")
        return True
    except SQLAlchemyError as e:
        db.session.rollback()
        logger.error(f"Error inserting dict: {e}")
        return False


def delete(id: str) -> bool:
    try:
        info = Dictionary.query.get(id)
        if info:
            db.session.delete(info)
            db.session.commit()
            logger.info(f"Deleted dict with id: {info.id}")
            return True
        logger.warning(f"User with id: {id} not found")
        return False
    except SQLAlchemyError as e:
        db.session.rollback()
        logger.error(f"Error deleting dict: {e}")
        return False


def get(page: int = 1, per_page: int = 10, category: str = None) -> dict:
    try:
        logger.info(
            f"Fetching dicts for page: {page}, per_page: {per_page}, category: {category}")
        query = Dictionary.query.order_by(Dictionary.timestamp.desc())
       
        if category is None:
            pass
        else:
            query = query.filter(Dictionary.category == category)
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False)
        items = [info.to_dict() for info in pagination.items]
        logger.info(
            f"Retrieved {len(items)} dicts from page {page}, total items: {pagination.total}, total pages: {pagination.pages}")
        return {
            "items": items,
            "total": pagination.total
        }
    except SQLAlchemyError as e:
        logger.error(f"Error retrieving dicts: {e}")
        return {
            "items": [],
            "total": 0
        }
    
def dict_category_kv(category: str = None) -> dict:
    try:
        logger.info(f"Fetching dictionary items for category: {category}")
        query = Dictionary.query
        
        if category:
            query = query.filter(Dictionary.category == category)
        
        items = query.all()
        result = {item.key: item.value for item in items}
        
        logger.info(f"Retrieved {len(result)} dictionary items for category: {category}")
        return result
    except SQLAlchemyError as e:
        logger.error(f"Error retrieving dictionary items: {e}")
        return {}
